package com.haoxuer.discover.weibo.rest.filter;

import com.haoxuer.discover.config.data.entity.User;
import com.haoxuer.discover.data.page.Filter;
import com.haoxuer.discover.filter.common.FilterChain;
import com.haoxuer.discover.filter.common.HandlerRequest;
import com.haoxuer.discover.filter.common.HandlerResponse;
import com.haoxuer.discover.user.service.UserTokenService;
import com.haoxuer.discover.weibo.api.domain.request.WeiboPostRequest;
import com.haoxuer.discover.weibo.data.dao.WeiBoDao;
import com.haoxuer.discover.weibo.data.entity.WeiBo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.util.Calendar;

@Scope("prototype")
@Component
public class TimeCheckFilter implements FilterProxy {


  @Autowired
  UserTokenService tokenService;

  @Autowired
  WeiBoDao weiBoDao;

  @Override
  public void doFilter(HandlerRequest handlerRequest, HandlerResponse response, FilterChain filterChain) {

    WeiboPostRequest request= (WeiboPostRequest) handlerRequest.getAttribute("request");
    if (StringUtils.isEmpty(request.getNote())) {
      response.setCode(501);
      response.setMsg("内容不能为空");
      return ;
    }
    Long id = tokenService.user(request.getUserToken());
    if (id == null) {
      response.setCode(502);
      response.setMsg("用户不存在");
      return ;
    }
    Calendar calendar = Calendar.getInstance();
    calendar.add(Calendar.SECOND, -10);
    WeiBo weiBo = weiBoDao.one(Filter.eq("user.id", id), Filter.ge("addDate", calendar.getTime()));
    if (weiBo!=null){
      response.setCode(503);
      response.setMsg("你的速度太快了");
      return ;
    }
    handlerRequest.setAttribute("user", User.fromId(id));
    filterChain.doFilter(handlerRequest,response);
  }
}
